package com._9xcloud.leaverequest.web.security;

import com._9xcloud.leaverequest.domain.Student;
import com._9xcloud.leaverequest.domain.Teacher;
import com._9xcloud.leaverequest.domain.User;
import com._9xcloud.leaverequest.service.StudentService;
import com._9xcloud.leaverequest.service.TeacherService;
import com._9xcloud.leaverequest.web.util.TokenUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * Created by hyq on 2015/5/21.
 */
public class UserService implements UserDetailsService {
    private TeacherService teacherService;
    private StudentService studentService;

    public UserService(TeacherService teacherService, StudentService studentService) {
        this.teacherService = teacherService;
        this.studentService = studentService;
    }

    public UserDetails loadUserByUsername(String userRoleAndName) throws UsernameNotFoundException {
        String roleName = TokenUtils.getRoleNameFromToken(userRoleAndName);
        String userName = TokenUtils.getUserNameFromToken(userRoleAndName);
        return loadUser(roleName, userName);
    }

    public User loadUser(String roleName, String userName) throws UsernameNotFoundException {
        if (Teacher.USER_ROLE.getAuthority().contentEquals(roleName)) {
            return teacherService.loadUserByUsername(userName);
        } else if (Student.USER_ROLE.getAuthority().contentEquals(roleName)) {
            return studentService.loadUserByUsername(userName);
        } else {
            throw new UsernameNotFoundException("Not Acceptable Role");
        }
    }
}
